package com.unionpay.upyzt.spring.example.service.unionPay.impl;


import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.unionpay.upyzt.exception.UpyztException;
import com.unionpay.upyzt.model.BalanceAcct;
import com.unionpay.upyzt.model.CusApplication;
import com.unionpay.upyzt.model.Media;
import com.unionpay.upyzt.resp.BalanceAcctResp;
import com.unionpay.upyzt.resp.CusApplicationResp;
import com.unionpay.upyzt.resp.CusApplicationSmsCodeResp;
import com.unionpay.upyzt.resp.MediaResp;
import com.unionpay.upyzt.spring.example.entity.Incoming;
import com.unionpay.upyzt.spring.example.service.unionPay.UnionPayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class UnionPayServiceImpl implements UnionPayService {
    @Autowired
    private Gson gson;


    @Override
    public Map<String, Object> getMobileVerificationCode(String phoneNumber) {
        Map<String, Object> map = new HashMap<>();
        map.put("mobile_number",phoneNumber );
        CusApplicationSmsCodeResp cusApplicationSmsCodeResp  = null;
        try {
            cusApplicationSmsCodeResp = CusApplication.sendSmsCode(map);
        } catch (UpyztException e) {
            throw new RuntimeException(e);
        }
        log.info("------- 个人用户进件-短信验证码 ------- {} ", cusApplicationSmsCodeResp.getMobileNumber());
        map.clear();
        map.put("cusApplicationSmsCodeResp",cusApplicationSmsCodeResp);
        return map;
    }

    public  void  disableSSl() throws KeyManagementException, NoSuchAlgorithmException {  // 禁用SSL证书验证
        TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            @Override
            public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
            }

            @Override
            public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
            }
        }};
// 创建SSLContext，使用禁用SSL证书验证的TrustManager
        SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());

// 设置全局默认的SSLSocketFactory，使RestTemplate使用禁用SSL证书验证的SSLContext
        HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());

    }

    @Override
    public Map<String, Object> personalValidationIncoming(Incoming incoming) {



        Map<String, Object> params = new HashMap<>();
        try {
            disableSSl();
            params.put("mobile_number", incoming.getMobileNumber());
            // 下载远程图片并写入临时文件
            File tempFile = null;
            File tempFile1 = null;
            MediaResp mediaResp = null;
            MediaResp mediaResp1 = null;
            try (InputStream in = new URL(incoming.getIdCard().getResourceLocation()).openStream()) {
                tempFile = File.createTempFile("temp_image", ".png");
                try (FileOutputStream fos = new FileOutputStream(tempFile)) {
                    byte[] buffer = new byte[1024];
                    int bytesRead;
                    while ((bytesRead = in.read(buffer)) != -1) {
                        fos.write(buffer, 0, bytesRead);
                    }
                }
                // 确保在上传后删除临时文件
                tempFile.deleteOnExit();

                // 调用Media.uploadImage()方法上传图片
                mediaResp = Media.uploadImage(tempFile);

                // 处理mediaResp...
            } catch (IOException e) {
                // 清理资源（如果有必要）
                if (tempFile != null && tempFile.exists()) {
                    tempFile.delete();
                }
                throw e; // 或者处理异常
            }
            try (InputStream in1 = new URL(incoming.getIdCard().getResourceBackLocation()).openStream()) {
                tempFile1 = File.createTempFile("temp_image", ".png");
                try (FileOutputStream fos1 = new FileOutputStream(tempFile1)) {
                    byte[] buffer1 = new byte[1024];
                    int bytesRead1;
                    while ((bytesRead1 = in1.read(buffer1)) != -1) {
                        fos1.write(buffer1, 0, bytesRead1);
                    }
                }
                // 确保在上传后删除临时文件
                tempFile1.deleteOnExit();

                // 调用Media.uploadImage()方法上传图片
                mediaResp1 = Media.uploadImage(tempFile1);

                // 处理mediaResp...
            } catch (IOException e) {
                // 清理资源（如果有必要）
                if (tempFile1 != null && tempFile1.exists()) {
                    tempFile1.delete();
                }
                throw e; // 或者处理异常
            }
//            MediaResp mediaResp = Media.uploadImage(ResourceUtils.getFile(incoming.getIdCard().getResourceLocation()));
//            MediaResp mediaResp1 = Media.uploadImage(ResourceUtils.getFile(incoming.getIdCard().getResourceBackLocation()));
            //MediaResp mediaResp = Media.uploadImage(ResourceUtils.getFile("classpath:static/id_card_sample.jpg"));
            incoming.getIdCard().setCopy(mediaResp.getMediaId());
            incoming.getIdCard().setNational(mediaResp1.getMediaId());
            System.out.println("------->"+ JSONObject.toJSONString(incoming.toMap()));
            CusApplicationResp cusApplicationResp = CusApplication.create(incoming.toMap());
            System.out.println("--->"+cusApplicationResp);
            BalanceAcctResp balanceAcctResp = BalanceAcct.retrieveById(cusApplicationResp.getBalanceAcctId());
            log.info("------- 电子账簿查询 ------- {} ", gson.toJson(balanceAcctResp));
            log.info("------- 个人用户首次进件 ------- {} ", cusApplicationResp.getBalanceAcctId());
            params.put("cusApplicationResp",cusApplicationResp);
            params.put("balanceAcctResp",balanceAcctResp);

            params.put("code",200);
        } catch (UpyztException | IOException e) {
            params.clear();
            params.put("code",400);
            params.put("data",e.getMessage());
            return params;
        } catch (NoSuchAlgorithmException | KeyManagementException e) {
            throw new RuntimeException(e);
        }
        return params;
    }
}
